"""
Redis 缓存实现（可选）

使用方法：
1. 安装 redis: pip install redis
2. 在 settings.py 中配置:
   from biz.utils.redis_cache import RedisCache
   cache = RedisCache(host='localhost', port=6379, db=0)
"""

import json
import uuid
from typing import Any, Optional, List, Dict
try:
    import redis
    REDIS_AVAILABLE = True
except ImportError:
    REDIS_AVAILABLE = False
    print("Warning: redis module not installed. Use 'pip install redis' to enable Redis cache.")

from cache import Cache


class RedisCache(Cache):
    """
    Redis 缓存实现
    
    优势：
    - 持久化存储
    - 支持分布式
    - 自动过期
    - 高性能
    """
    
    def __init__(
        self,
        host: str = 'localhost',
        port: int = 6379,
        db: int = 0,
        password: Optional[str] = None,
        default_ttl: int = 3600,
        key_prefix: str = 'vanna:'
    ):
        """
        初始化 Redis 缓存
        
        Args:
            host: Redis 主机
            port: Redis 端口
            db: Redis 数据库编号
            password: Redis 密码
            default_ttl: 默认过期时间（秒）
            key_prefix: 键前缀
        """
        if not REDIS_AVAILABLE:
            raise ImportError("redis module is required. Install it with: pip install redis")
        
        self.client = redis.Redis(
            host=host,
            port=port,
            db=db,
            password=password,
            decode_responses=True
        )
        self.default_ttl = default_ttl
        self.key_prefix = key_prefix
        
        # 测试连接
        try:
            self.client.ping()
        except redis.ConnectionError as e:
            raise ConnectionError(f"Failed to connect to Redis: {e}")
    
    def _make_key(self, id: str) -> str:
        """生成 Redis 键"""
        return f"{self.key_prefix}{id}"
    
    def generate_id(self, *args, **kwargs) -> str:
        """生成唯一ID"""
        return str(uuid.uuid4())
    
    def set(self, id: str, field: str, value: Any, ttl: Optional[int] = None):
        """
        设置缓存值
        
        Args:
            id: 缓存ID
            field: 字段名
            value: 值
            ttl: 过期时间（秒）
        """
        key = self._make_key(id)
        
        # 序列化复杂对象
        if not isinstance(value, (str, int, float, bool, type(None))):
            try:
                value = json.dumps(value, default=str)
            except (TypeError, ValueError):
                # 如果无法序列化，转为字符串
                value = str(value)
        
        # 使用 hash 存储字段
        self.client.hset(key, field, value)
        
        # 设置过期时间
        ttl = ttl if ttl is not None else self.default_ttl
        self.client.expire(key, ttl)
    
    def get(self, id: str, field: str) -> Optional[Any]:
        """
        获取缓存值
        
        Args:
            id: 缓存ID
            field: 字段名
            
        Returns:
            缓存值，如果不存在返回 None
        """
        key = self._make_key(id)
        value = self.client.hget(key, field)
        
        if value is None:
            return None
        
        # 尝试反序列化 JSON
        try:
            return json.loads(value)
        except (json.JSONDecodeError, TypeError):
            return value
    
    def get_all(self, field_list: List[str]) -> List[Dict[str, Any]]:
        """
        获取所有缓存条目的指定字段
        
        Args:
            field_list: 要获取的字段列表
            
        Returns:
            包含所有条目的列表
        """
        pattern = f"{self.key_prefix}*"
        result = []
        
        for key in self.client.scan_iter(match=pattern):
            id = key.replace(self.key_prefix, '')
            item = {"id": id}
            
            for field in field_list:
                value = self.get(id, field)
                item[field] = value
            
            result.append(item)
        
        return result
    
    def delete(self, id: str):
        """删除缓存条目"""
        key = self._make_key(id)
        self.client.delete(key)
    
    def clear(self):
        """清空所有缓存"""
        pattern = f"{self.key_prefix}*"
        for key in self.client.scan_iter(match=pattern):
            self.client.delete(key)
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计信息"""
        pattern = f"{self.key_prefix}*"
        total_keys = sum(1 for _ in self.client.scan_iter(match=pattern))
        
        info = self.client.info('memory')
        
        return {
            "total_entries": total_keys,
            "used_memory": info.get('used_memory_human', 'N/A'),
            "used_memory_peak": info.get('used_memory_peak_human', 'N/A'),
            "connected_clients": self.client.client_list().__len__()
        }
    
    def extend_ttl(self, id: str, additional_seconds: int):
        """延长缓存条目的过期时间"""
        key = self._make_key(id)
        current_ttl = self.client.ttl(key)
        if current_ttl > 0:
            self.client.expire(key, current_ttl + additional_seconds)
